<!--
* description: 规则维护
* author:wangjuan
* createdDate:2020-12-4
-->
<template>
  <section class="editBigAreaInfo">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :title="textMap[popupsState]"
      :append-to-body="true"
      :visible.sync="curPopupsVisible"
      width="45%"
      @close="closeEdit"
      @opened="open"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />

      <div class="filter-container filter-params">
        <el-row ref="vailComponentList" :gutter="26">
          <one-table-template
            ref="multipleTable"
            :dynamic-buttons="tableButtons"
            :dynamic-components="tableComponents"
            :dynamic-api-config="apiConfig"
            :dynamic-form-fields="formField"
            :dynamic-is-show-select="true"
            :dynamic-is-show-more-btn="true"
            :dynamic-is-init-table="false"
          />
        </el-row>
      </div>

      <div slot="footer" class="dialog-footer">
        <!-- <el-button
          v-for="comp in tableButtons"
          :key="comp.compKey"
          :type="comp.type"
          :icon="comp.icon"
          @click="comp.clickEvent"
          >{{ comp.text }}</el-button
        > -->
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { formMixins } from "@/components/mixins/formMixins";
import OneTableTemplate from "@/components/templates/oneTable";
import { vehiclePdiPriceInquirys } from "@/api/se/vehiclePdiPriceInquiry";

export default {
  components: {
    dialogHeader: () => import("@/components/dialogHeader"),
    mixButton: () => import("@/components/basicComponent/mixButton"),
    OneTableTemplate
  },

  // 组件混入对象
  mixins: [formMixins],

  props: {
    popupsVisible: { type: Boolean, default: false },
    // 从网格传入的编辑行数据(json)
    dynamicEditRowData: {
      type: Object,
      default: function() {
        return {};
      }
    }
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path;

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode]);
    return {
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: "btnKey1",
          type: "primary",
          size: "small",
          icon: "iconfont  icon-preservation",
          clickEvent: () => this.save(),
          text: this.$t("sys.button.save") /* 保存*/,
          position: "right"
        },
        {
          compKey: "btnKey2",
          type: "",
          size: "small",
          icon: "iconfont  icon-cancel",
          clickEvent: () => this.close(),
          text: this.$t("sys.button.cancel") // 取消
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents
          : [
              {
                compKey: "compKey1",
                labelName: "授权内容说明：",
                codeField: "remark",
                component: () =>
                  import("@/components/org/commonInput/textareaInput"),
                type: "inputText",
                isRequire: true,
                isMust: true,
                span: 24
              },
              {
                compKey: "compKey3",
                labelName: "效验类型：",
                codeField: "preType",
                textField: "preTypeName",
                component: () => import("@/components/org/commonSelect"),
                customObj: {
                  api: vehiclePdiPriceInquirys.queryType
                },
                type: "dropdownList",
                isRequire: true,
                isMust: true,
                span: 24
              },
              {
                compKey: "compKey2",
                labelName: "最低效验值：",
                codeField: "partSum",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                isRequire: true,
                isMust: true,
                span: 24
              },
              {
                compKey: "compKey4",
                labelName: "效验（备件编码/工时代码）：",
                codeField: "preName",
                textField: "preCode",
                // component: () => import("@/views/ve/planReport/components/multipleSearchInput"),
                component: () => import("@/components/se/rulesSet"),
                type: "inputText",
                dataToObject: {
                  // 控制弹窗页面 搜索 网格 元素
                  tableComponents: [
                    {
                      compKey: 'compKey1',
                      labelName: '编码：',
                      codeField: 'preCode',
                      component: () => import('@/components/org/commonInput'),
                      type: 'inputText',
                      isMust: true,
                      span: 8
                    },
                    {
                      compKey: 'compKey2',
                      labelName: '名称：',
                      codeField: 'preName',
                      component: () => import('@/components/org/commonInput'),
                      type: 'inputText',
                      isMust: true,
                      span: 8
                    }
                  ],
                  tableCols: [
                    {
                      prop: 'preCode',
                      label: '工时编码'
                    },
                    {
                      prop: 'preName',
                      label: '工时名称'
                    }
                  ],
                  formField: {
                    preType: '',
                    preCode: '',
                    preName: '',
                    repairContent: '',
                  },
                  preTypeStandby: '',
                  oFields: 'preName,preCode',
                  restData: ['preName','preCode','repairContent'],
                  returnField: {
                    prop: 'preName',
                    label: '工时名称',
                    prop: 'preType',
                  },
                  api: vehiclePdiPriceInquirys.timeCodeWindow
                },  
                isMust: true,
                span: 24
              },
              {
                compKey: "compKey4",
                labelName: "效验（备件名称/维修内容）：",
                codeField: "preName",
                component: () => import("@/components/org/commonInput"),
                type: "inputText",
                disabled: true,
                isMust: true,
                span: 24
              }
            ],

      // 标题
      textMap: {
        edit: "规则设置",
        add: "规则设置"
      },
      // 表单数据（无需赋值，由混入对象赋值）
      formField: this.$utils.getFormField(
        this,
        {
          remark: "", //授权内容说明
          preType: "", //效验类型
          preCode: "", //工效验(备件编码/工时代码)
          preName: "", //效验(备件名称/维修内容)
          partSum: "",
          preRuleId: "",
          preTypeName: ""
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      )
    };
  },
  watch: {
    'formField.preType': {
      handler(newval,oldval) {
        if(this.formField.preType === '备件'){
          this.formField.preType = "1"
          this.tableComponents[3].dataToObject.formField.preType = '1'
        } 
        if (this.formField.preType === '工时'){
          this.formField.preType = "2"
          this.tableComponents[3].dataToObject.formField.preType = '2'
        }
        
        if(newval) {
          this.tableComponents[3].disabled = false
          if(newval === '1') {
            this.formField.preType = "1"
            this.tableComponents[3].dataToObject.formField.preType = '1'

            this.tableComponents[3].dataToObject.tableCols[0].label = '备件编码'
            this.tableComponents[3].dataToObject.tableCols[1].label = '备件名称'
            this.tableComponents[3].dataToObject.tableCols[1].prop = 'preName'
            // 搜索框
            this.tableComponents[3].dataToObject.tableComponents[1].labelName = '名称：'
            this.tableComponents[3].dataToObject.tableComponents[1].codeField = 'preName'
            this.tableComponents[3].dataToObject.tableComponents[1].compKey = this.tableComponents[3].dataToObject.tableComponents[1].compKey+'1'
          } else if(newval === '2') {
            this.formField.preType = "2"
            this.tableComponents[3].dataToObject.formField.preType = '2'

            this.tableComponents[3].dataToObject.tableCols[0].label = '工时编码'
            this.tableComponents[3].dataToObject.tableCols[1].label = '维修内容'
            this.tableComponents[3].dataToObject.tableCols[1].prop = 'preName'
            // 搜索框
            this.tableComponents[3].dataToObject.tableComponents[1].labelName = '内容：'
            this.tableComponents[3].dataToObject.tableComponents[1].codeField = 'preName'
            this.tableComponents[3].dataToObject.tableComponents[1].compKey = this.tableComponents[3].dataToObject.tableComponents[1].compKey+'1'
          }
        } else {
          this.tableComponents[3].disabled = true
          this.formField.preType = oldval
          this.tableComponents[3].dataToObject.formField.preType = oldval
        }
        if(newval !== oldval) {
          this.formField.preCode = ""
          this.formField.preName = ""
          this.formField.preType = newval
          this.tableComponents[3].dataToObject.formField.preType = newval
        }
        //给备用preType赋值
        this.tableComponents[3].dataToObject.preTypeStandby=this.formField.preType
      },
      immediate: true,
      deep: true
    },
  },

  methods: {
    closeEdit() {
      this.$emit("close");
      this.$emit("update:curPopupsVisible", false);
    },
    // 新增/编辑保存按钮
    save() {
      // 非空校验
      this.$utils.validataMoth(this, "validpopup");
      if (this.valid) {
        if (this.popupsState === "edit") {
          this.editSave();
        } else {
          this.addSave();
        }
      }
    },
    // 编辑保存
    editSave() {
      const that = this;
      const queryObj = {
        // 保存mutation
        type: "mutation",
        // api配置
        apiConfig: {
          APIUrl: "/mp/e3sh/aftersale/preauthorizationservice/UpAdd.do"
        },
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: that.formField
      };
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj);
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === "1") {
          this.$message({
            message: this.$t("sys.tips.esTip5") /* 保存成功*/,
            type: "success",
            duration: 1000
          });
          this.curPopupsVisible = false;
          this.$nextTick(() => {
            this.$parent.queryTable(1);
          });
        } else {
          // 保存失败
          this.$message({
            message: "保存失败:" + response.msg,
            type: "warn",
            uration: 1000
          });
        }
        // this.curPopupsVisible = false;
      });
    },
    // 新增保存
    addSave() {
      const queryObj = {
        // 保存mutation
        type: "mutation",
        // api配置
        apiConfig: {
          APIUrl: "/mp/e3sh/aftersale/preauthorizationservice/Addl.do"
        },
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: this.formField
      };
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj);
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === "1") {
          this.$message({
            message: "添加成功",
            type: "success",
            duration: 1000
          });
          this.curPopupsVisible = false;
          this.$nextTick(() => {
            this.$parent.queryTable(1);
          });
        } else {
          // 保存失败
          this.$message({
            message: "添加失败:" + response.msg,
            type: "warn",
            uration: 1000
          });
        }
        // this.curPopupsVisible = false;
      });
    },
    open() {
      const queryObj = {
        // 保存mutation
        type: "mutation",
        // api配置
        apiConfig: {
          APIUrl: "/mp/e3sh/aftersale/preauthorizationservice/queryType.do"
        },
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {}
      };
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj);
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {});
      if (this.popupsState === "edit") {
        this.formField.remark = this.dynamicEditRowData.remark;
        this.formField.preType = this.dynamicEditRowData.preType;
        this.formField.preCode = this.dynamicEditRowData.preCode;
        this.formField.preName = this.dynamicEditRowData.preName;
        this.formField.partSum = this.dynamicEditRowData.partSum;
        this.formField.preRuleId = this.dynamicEditRowData.preRuleId;
        // this.formField.preType2 = this.dynamicEditRowData.preType2;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.promptSpan {
  position: absolute;
  bottom: 26px;
  right: 335px;
  color: #e70020;
}
</style>

